package NW_EM;

import java.util.List;
import java.util.Random;

import NWPackage.Cell;
import NWPackage.PairPreferdCandidateCell;
import NWPackage.PairPreferdCandidateMatrix;
import NWPackage.ProbabilitiesMatrix;
import NWPackage.Protocol;
import NWPackage.QueryFinderAlg;

public class EM_Borda_Second_Winner implements QueryFinderAlg{
	
    Random rand;
    Random rand2;
    
    public EM_Borda_Second_Winner(int seed){
    	rand = new Random(seed);
    	rand2 = new Random(seed);
    }

    
    //I ADDED TO PAIRPREFEREDCANDIDATE A METHOD CALLED RELEVANTTRIOS PAERHPAS USE IT?
    
	@Override
	public Cell FindNextQuery(ProbabilitiesMatrix probMatrix,PairPreferdCandidateMatrix pairsPreferredMatrix,List<String> optionalWinners, Protocol protocol) throws Exception {
		// find max in NW table - find itemA				
				List<String> maxItems = protocol.findMaxCandidate(optionalWinners);
				//choose randomly from pool of cands:
				int x = rand2.nextInt(maxItems.size());				
				String itemA = maxItems.get(x);
				//find 2nd max
				List<String> maxItemBs = protocol.find2ndMaxCand(optionalWinners, itemA);
				int y = rand2.nextInt(maxItemBs.size());
				String itemB = maxItems.get(y);
				int pickIndex = -1;
				PairPreferdCandidateCell cellQ;
				boolean flag = false;
				int counter = 0;
				do{
					int limit = pairsPreferredMatrix.getLength();
					pickIndex = rand.nextInt(limit);
					cellQ = pairsPreferredMatrix.getCell(pickIndex);
					String [] cands = cellQ.getCandidates();			
			        if( (cands[0].equals(itemA))||(cands[1].equals(itemA)))  //if one of the chosen item is a MAX
			        	if( (cands[0].equals(itemB))||(cands[1].equals(itemB))  ) //if one of the chosen is the 2nd MAX
			        	if (cellQ.isExistIn(optionalWinners))  //and the chosen query is an option
			        		if (cellQ.getPrefered_C() == null )  //if we didn't ask it already
			                  flag = true;
			        counter++;
			     //   if (counter>850)
			       // 	System.out.println("counter=" + counter+" limit=" + limit + " index="+ pickIndex);			        						        
				}
				while (!(flag));
				
				return cellQ;			
				
		
	}
	

}
